﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using ThuVien;

namespace TranTekBE
{
    public partial class CategoryMgmt : PageRequireLogin
    {
        private string SortBy
        {
            set
            {
                ViewState["SortBy"] = value;
            }
            get
            {
                if (ViewState["SortBy"] != null)
                    return ViewState["SortBy"].ToString();
                return "catShowSeq";
            }
        }

        private string SortDirect
        {
            set
            {
                ViewState["SortDirect"] = value;
            }
            get
            {
                if (ViewState["SortDirect"] != null)
                    return ViewState["SortDirect"].ToString();
                return "ASC";
            }
        }

        private int PageCount
        {
            set
            {
                ViewState["PageCount"] = value;
            }
            get
            {
                return FunctionsUtils.ConvertToInt(ViewState["PageCount"], 1);
            }
        }
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Form["__EVENTTARGET"] == "Button2")
            {
                //fire event
                //btnDelete_Click(this, new EventArgs());
            }

            this.Page.Form.DefaultButton = btnSearch.UniqueID;
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadJS", "LoadJS();", true);

            if (Page.IsPostBack == false)
            {
                this.GetListPageSize(ddlPageSize);

                this.LoadCategories();
            }
        }

        private void LoadCategories()
        {
            ltError.Text = string.Empty;
            try
            {
                string sSearch = this.CreateSearchCondition();

                //get Total Record de tinh page count
                DataSet ds1 = FunctionsUtils.Database.ExecuteQuery(sSearch);
                
                int currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);                
                int pageSize = FunctionsUtils.ConvertToInt(ddlPageSize.SelectedValue, FunctionsUtils.ConvertToInt(FunctionsUtils.GetConfigValue("PageSize"), 50));
                //int pageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                this.PageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                ds1.Dispose();

                currPage = FunctionsUtils.GetCurrPage(currPage, this.PageCount);
                ltPage.Text = string.Format("&nbsp;{0} of {1}&nbsp;", currPage, this.PageCount);
                txtGoPage.Text = currPage.ToString();

                SetButtonPageNavigationStatus(currPage, this.PageCount);
                
                //DataSet ds = FunctionsUtils.Database.ExecuteQuery(sSearch);
                DataSet ds = FunctionsUtils.Database.ExecuteQuery(sSearch, currPage, pageSize);

                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    rpCategory.DataSource = ds;
                    rpCategory.DataBind();
                    ltNoRecord.Visible = false;

                    if (this.PageCount == 1)
                    {
                        phPageNavigation.Visible = false;
                    }
                    else
                    {
                        phPageNavigation.Visible = true;
                    }
                }
                else
                {
                    rpCategory.DataSource = null;
                    rpCategory.DataBind();
                    ltNoRecord.Visible = true;
                    phPageNavigation.Visible = false;
                    //ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "NoRC", "HidePageNav();", true);
                }
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in Load Categories: {0} {1}", ex, ex.StackTrace);
            }
        }

        private string CreateSearchCondition()
        {
            string sSearch = "Select * From Vw_Category Where CategoryISN > 0 ";

            if (txtCategoryName.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And catName like '%{0}%' ", FunctionsUtils.DoubleSingleQuote(txtCategoryName.Text.Trim()));
            }

            if (ddlStatus.SelectedValue.Length > 0)
            {
                sSearch += string.Format("And catStatus = '{0}' ", ddlStatus.SelectedValue);
            }

            if (txtCategoryDesc.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And catDesc like '%{0}%' ", FunctionsUtils.DoubleSingleQuote(txtCategoryDesc.Text.Trim()));
            }

            //sSearch += string.Format("Order By {0} {1}", this.SortBy, this.SortDirect);
            sSearch += string.Format("Order By {0} {1}", ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);

            return sSearch;
        }

        //public string GetCategoryStatus(object value)
        //{
        //    int statusCode = FunctionsUtils.ConvertToInt(value, 0);

        //    if (statusCode == 1)
        //        return "Yes";
        //    else
        //        return "No";
        //}

        protected void btnClearSearch_Click(object sender, ImageClickEventArgs e)
        {
            txtCategoryName.Text = string.Empty;
            ddlStatus.SelectedIndex = 0;
            txtCategoryDesc.Text = string.Empty;
            this.LoadCategories();
        }

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.LoadCategories();
        }

        protected void Sort_Click(object sender, EventArgs e)
        {
            LinkButton lbt = sender as LinkButton;

            string CommandArgument = string.Empty;
            string css = string.Empty;
            if (lbt.CommandArgument.ToUpper() == "DESC")
            {
                CommandArgument = "ASC";
                css = "sortAsc";
            }
            else
            {
                CommandArgument = "DESC";
                css = "sortDesc";
            }

            //remove sort o cac link button khac
            this.RemoveSortCss();

            lbt.CommandArgument = CommandArgument;
            lbt.CssClass = "GridHeader " + css;
            //this.SortBy = lbt.CommandName;
            //this.SortDirect = CommandArgument;

            FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
            FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);

            this.LoadCategories();
        }

        //private void RemoveSortCss()
        //{
        //    List<LinkButton> allControls = new List<LinkButton>();
        //    GetControlList<LinkButton>(Page.Controls, allControls);
        //    foreach (var childControl in allControls )
        //    {
        //        if (((LinkButton)childControl).CommandArgument.Length > 0)
        //            ((LinkButton)childControl).CssClass = "GridHeader";
        //    }
        //}

        //private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection)
        //where T : Control
        //{
        //    foreach (Control control in controlCollection)
        //    {
        //        if (control is T) // This is cleaner
        //            resultCollection.Add((T)control);

        //        if (control.HasControls())
        //            GetControlList(control.Controls, resultCollection);
        //    }
        //}

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (hdList.Value.Length > 0)
                {
                    FunctionsUtils.Database.ExecuteStoredProcReturnObject("xp_category_muldel", new string[] { "lstCategoryISN" }, new object[] { hdList.Value });
                    this.LoadCategories();
                }
            }
            catch(Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in Delete Categories: {0} {1}", ex, ex.StackTrace);
            }
        }

        protected void ControlClick_Command(object sender, CommandEventArgs e)
        {
            int currPage = 0;
            switch (e.CommandName)
            {
                case "Delete":
                    this.DeleteCategory();
                    break;
                case "Sort":
                    //remove sort o cac link button khac
                    this.RemoveSortCss();

                    //FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
                    //FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);
                    this.SetSortAtributeForLinkButton(ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);
                    this.LoadCategories();
                    break;
                case "GoToPage":
                    this.LoadCategories();
                    break;
                case "GoToPrev":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);
                    if (currPage > 1)
                    {
                        currPage -= 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this.LoadCategories();
                    break;
                case "GoToNext":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);

                    if (currPage < this.PageCount)
                    {
                        currPage += 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this.LoadCategories();
                    break;
            }
        }

        private void DeleteCategory()
        {
            try
            {
                if (hdList.Value.Length > 0)
                {
                    FunctionsUtils.Database.ExecuteStoredProcReturnObject("xp_category_muldel", new string[] { "lstCategoryISN" }, new object[] { hdList.Value });
                    this.LoadCategories();
                }
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in Delete Categories: {0} {1}", ex, ex.StackTrace);
            }
        }

        //private void SetSortAtributeForLinkButton(string sortBy, string sortDirect)
        //{
        //    string css = "sortDesc";
        //    if (sortDirect.Equals("ASC") == true)
        //    {
        //        css = "sortAsc";
        //    }

        //    List<LinkButton> allControls = new List<LinkButton>();
        //    GetControlList<LinkButton>(Page.Controls, allControls);
        //    foreach (var childControl in allControls)
        //    {
        //        if (((LinkButton)childControl).CommandName.Equals(sortBy) == true)
        //        {
        //            //((LinkButton)childControl).CommandName = sortBy;
        //            ((LinkButton)childControl).CommandArgument = sortDirect;
        //            ((LinkButton)childControl).CssClass = "GridHeader " + css;
        //        }
        //    }
        //}

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.LoadCategories();
        }

        private void SetButtonPageNavigationStatus(int currPage, int pageCount)
        {
            if (currPage == 1)
            {
                btnPrev.Enabled = false;
            }
            else
            {
                btnPrev.Enabled = true;
            }

            if (currPage == pageCount)
            {
                btnNext.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
            }
        }

        //public void GetListPageSize(DropDownList ddl)
        //{
        //    string[] arrPageSize = FunctionsUtils.GetConfigValue("ListPageSizes").Split(',');
        //    for (int i = 0; i < arrPageSize.Length; i++)
        //    {
        //        ddl.Items.Add(new ListItem(arrPageSize[i], arrPageSize[i]));
        //    }
        //    FunctionsUtils.SelectItemInControlList(ddl, FunctionsUtils.GetConfigValue("PageSize"), SelectBy.Value);
        //}
    }
}
